package com.android.happymall.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.happymall.activity.mine.TransparentActivity;
import com.android.happymall.model.detail.paydetail;
import com.android.happymall.model.detail.paydetailCallback;
import com.android.happymall.model.detail.paydone;
import com.android.happymall.model.detail.paydoneCallback;
import com.android.happymall.model.detail.paydonetoshare;
import com.android.happymall.model.detail.wchatpaydoneCallback;
import com.android.happymall.utils.HttpUtils;
import com.android.happymall.utils.MyLog;
import com.android.happymall.utils.ObjectUtils;
import com.android.happymall.R;
import com.android.happymall.app.BaseActivity;
import com.android.happymall.model.MainTabData;
import com.android.happymall.model.detail.paydonetoshareCallback;
import com.android.happymall.model.detail.wchatpaydone;
import com.android.happymall.utils.ConstantsUrl;
import com.android.happymall.utils.LoginState;
import com.android.happymall.utils.alipay.PayResult;
import com.android.happymall.view.detail.PopPaycoupn;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


public class PayActivity extends BaseActivity implements TextWatcher {
    @BindView(R.id.pay_goods_store_name)
    TextView payGoodsStoreName;
    @BindView(R.id.pay_goods_thumb)
    ImageView payGoodsThumb;
    @BindView(R.id.pay_goods_title)
    TextView payGoodsTitle;
    @BindView(R.id.pay_goods_price_team)
    TextView payGoodsPriceTeam;
    @BindView(R.id.pay_goods_price)
    TextView payGoodsPrice;
    @BindView(R.id.pay_goods_price_spec)
    TextView payGoodsPriceSpec;
    @BindView(R.id.btn_minus)
    Button btnMinus;
    @BindView(R.id.edit_num)
    EditText editNum;
    @BindView(R.id.btn_plus)
    Button btnPlus;
    @BindView(R.id.pay_coupon_store_tv)
    TextView payCouponStoreTv;
    @BindView(R.id.pay_coupon_store_ll)
    LinearLayout payCouponStoreLl;
    @BindView(R.id.pay_msg_edit)
    EditText payMsgEdit;
    @BindView(R.id.pay_price_total)
    TextView payPriceTotal;
    @BindView(R.id.pay_price_deposit)
    TextView payPriceDeposit;
    @BindView(R.id.pay_price_deposit_ll)
    LinearLayout payPriceDepositLl;
    @BindView(R.id.pay_radio_express)
    RadioButton payRadioExpress;
    @BindView(R.id.pay_radio_self)
    RadioButton payRadioSelf;
    @BindView(R.id.pay_address_add_ll)
    LinearLayout payAddressAddLl;
    @BindView(R.id.pay_address_nameaphone)
    TextView payAddressNameaphone;
    @BindView(R.id.pay_address_address)
    TextView payAddressAddress;
    @BindView(R.id.pay_address_ll)
    LinearLayout payAddressLl;
    @BindView(R.id.pay_address_self_ll)
    NestFullListView payAddressSelfLl;
    @BindView(R.id.pay_coupon_general_tv)
    TextView payCouponGeneralTv;
    @BindView(R.id.pay_coupon_general_ll)
    LinearLayout payCouponGeneralLl;
    @BindView(R.id.pay_coupon_teamer_tv)
    TextView payCouponTeamerTv;
    @BindView(R.id.pay_coupon_teamer_ll)
    LinearLayout payCouponTeamerLl;
    @BindView(R.id.pay_style_list)
    NestFullListView payStyleList;
    @BindView(R.id.pay_tip)
    TextView payTip;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.pay_balance_use)
    CheckBox payBalanceUse;
    @BindView(R.id.pay_price_pay)
    TextView payPricePay;
    @BindView(R.id.pay_post)
    TextView payPost;
    @BindView(R.id.pay_address_self_empty_tv)
    TextView pay_address_self_empty_tv;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    @BindView(R.id.pay_radio_ll)
    RadioGroup payRadioLl;
    @BindView(R.id.pay_address)
    FrameLayout payAddress;
    @BindView(R.id.pay_address_take_ll)
    FrameLayout pay_address_take_ll;
    private boolean networkConnected;
    private Double price_team;
    private int typeid;
    private String common_id = "";
    private ArrayList<MainTabData> mSortListdata = new ArrayList<>();
    private PayActivity mcontext;
    private paydetail.DataBean data;
    private boolean isReallyOrder_flag;
    private String detail_id;
    private String spec = "";
    private String addressid = null;
    private int buy_num_limit = 1;
    private String token;
    private int buy_num;
    private int pospay = 0;
    private int posexpress = -1;
    private String[] pay_ids = new String[2];
    private String  pay_id = "42";
    private String pay_style;
    private String take_address_id = "0";
    private String express_id = "12";
    private double deposit;
    private String option = "";
    private  MainTabData weixindata = new MainTabData();
    private  MainTabData apliydata = new MainTabData();
    private SharedPreferences sharedPreferences;
    /** 支付宝支付业务：入参app_id */
    public static final String APPID = "2017051007189701";
    /** 支付宝账户登录授权业务：入参pid值 */
    public static final String PID = "2088911179397641";
    /** 支付宝账户登录授权业务：入参target_id值 */
    public static final String TARGET_ID = "111111";
    /** 微信注册类 */
    private IWXAPI iwxapi;
    private String orderInfo;
    private String order_sn="";
    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /** 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1 */
    public static final String RSA2_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC5loBf11d2wsXrEyxqy5TKB+pmY2io+5tsl6tsqCviWuphtfdvqlto+7l/z0ttnhL"
            + "k8yLfuIgYgVfveHsFcD7s3+K03MDvEfkgbqzMfr7CxIDdAULwsmR/kJuTt9Lhh0DH3D+ERj6IVFxCxPPGbj+5QAyXt5JwUbNH7c8NK6OeCORyt8z7U9GRe2n0SeIghrdgbWcFIwUjSOF"
            + "5eOW5YXEgEYrbE0xYmRiEWp113lkVDgcQvxZdZWwSFtACUqAUYA2nBkxUNTQQeOXuAF0V/FLabSOH2FW1OIPuSV2areH7Y3XlTO5dgMKbbdn7n1XjxjkaUlBRoktoeB2EUAv6tyBBAgMBAAECgg"
            + "EAYkN5vUU7njoKqSkBv5oDMeV3Crdf1vlBlgHIVkPE2JjiuNGsLYe51qBR24ZanbOwtWC2+lWuWatCcB0OphaEes8gLjskPHD7w1xWSgBh6KY6xMnCM8eAxro+ZbxS/+6pMik/yD2ZJn3kS8YUfO"
            + "ArBV8QS9R6yNW5Y0Ba/NI6U5XgdPg47qEVAKKjE+el0i1ecuR8h2MAQ1YkPEze7uz+I37n3r3TNVQ5fECZ6Nn6xD4wLQpslJMaUJ6uw0PJMoH2e1srDl6CJU7c74qY+Q/c22DAzv0XwI4Yu8Pi4Z"
            + "IUtNHX9JkJBJ/lgZoCpo2vdHVZbm9cbNOFjqhNsgQ4gnrkMQKBgQD8R9WRn3LyK8NMQx89BeKI+p1tl1MCcU5S5k4YTKLBh0Cs74V/OrhY0TEL5+WTcInbQrn/GXWkQ1ye9Nq1jQRmJF2M+gvqh5"
            + "ttOR4EFeSH6LugLgkmXj87cX3uTPAKr2vsyjwFLSb7g/TN/sfhg7XsxvLi364tEKYqx58sLe1avwKBgQC8UvQSShGn0TKVv/XlzmSrwS74uL37gczv/8khNJZ0sPKK5Wc/JmGKIrHywAWNf4DsAn"
            + "g6LuX2OpvcG7P3Ow0XWAjQhAZI0+beYW7e8vv651LQWDOlg/aHek+t8V4umH9ORixIyg/eZMNpDu3HZpvlfA+zHffg0/SPmHfId5FE/wKBgQCPX0+rc7+Ci4ZxB9BwALEugacISjCducD2cfY97w"
            + "esDm6eGX13wepUZ4aFKqQY96MQ3coQhOqLkNDJcYP+G4c9eTtFTDGLdsfI+eXqEnsPFh/TN3ZxvKwY3zXfQRBGMk2Wg5Q6qN93nxV4IGx96Dlyt9n/P3mgGM8mjs4R8IPsxwKBgBttlYCoawPfExf"
            + "+Wkj7E2x0eWveNEVSNU/rGBcO+q7KKrkSCkSHSYN95B7v2p8uJ8+32FzZAcMn7BVVr5NddV2mA7qiz+uBeUmANU6hYxO65zPS9MqxepFmvf4eflIZAcmbrM15KHCCinddpkH5btEwjXTP8486L49O"
            + "bHu09mJvAoGAEMaUtRKXx+hdWm1MTgDYqDZO158RKLmlCrvT8+aT1Li3k0e+J6Agus4nCCUnzk3TYH3Ij/c4tYNCz35md9llhsoyFMsM9DFlTtFF3fh1vox7Kk3HegQ1UT1pL/Dazv1gY0Jql4gbR7wbqirDixC+oHq8J18+UjfirZkTfxknJNY=";

    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。

                        Toast.makeText(mcontext, "支付成功", Toast.LENGTH_SHORT).show();
                        GetToSharePage();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        MyLog.e("zhibaoerror", resultInfo.toString());
                        Toast.makeText(mcontext, "支付失败", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        ButterKnife.bind(this);
        mcontext = PayActivity.this;
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        initTitle(0, "轻松团");
        initUI();
    }

    @Override
    protected void onResume() {
        super.onResume();
        buy_num = Integer.parseInt(editNum.getText().toString().trim());
        Getdata(detail_id, buy_num, typeid + "", spec, common_id, option);

    }

    private boolean isCheck = true;

    private void initUI() {

        detail_id = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_ID);
        typeid = getIntent().getIntExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_TYPEID, 0);
        buy_num = Integer.parseInt(getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_NUM));
        spec = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_SPEC);
        common_id = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_COMMON_ID);
        option = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_PAY_OPTION);

        payRadioExpress.setChecked(true);
        payAddress.setVisibility(View.VISIBLE);
        pay_address_take_ll.setVisibility(View.GONE);
        payRadioLl.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                int radioButtonId = radioGroup.getCheckedRadioButtonId();
                if (radioButtonId == R.id.pay_radio_express) {
                    isCheck = true;
                    express_id = "12";
                    payAddress.setVisibility(View.VISIBLE);

                    pay_address_take_ll.setVisibility(View.GONE);
                } else {
                    isCheck = false;
                    express_id = "10";
                    pay_address_take_ll.setVisibility(View.VISIBLE);
                    payAddress.setVisibility(View.GONE);


                }

            }
        });

        editNum.setText(buy_num + "");
        editNum.addTextChangedListener(this);
        buy_num = Integer.parseInt(editNum.getText().toString().trim());
        //  Getdata(detail_id, buy_num, typeid + "", spec, common_id, option);

    }

    //团长
    private double discount_teamer = 0.0;
    //通用
    private int pos_use_general;
    private String coupon_id_use_general = "0";
    private String coupon_discount_use_general = "0";
    private String coupon_need_amount_use_general = "-1";
    private String coupon_title_use_general = "不使用优惠券";
    //店铺
    private int pos_use_store;
    private String coupon_id_use_store = "0";
    private String coupon_discount_use_store = "0";
    private String coupon_need_amount_use_store = "-1";
    private String coupon_title_use_store = "不使用优惠券";

    @OnClick({R.id.btn_minus, R.id.btn_plus, R.id.pay_address_add_ll, R.id.pay_address_ll, R.id.click_resetnetwork_refresh,
            R.id.pay_post, R.id.pay_coupon_store_ll, R.id.pay_coupon_general_ll})
    public void onClick(View view) {
        Intent intent = new Intent(this, TransparentActivity.class);
        switch (view.getId()) {
            case R.id.btn_minus:
                if (editNum.getText().toString().trim().equals("")) {
                    editNum.setText("1");

                } else {
                    buy_num = Integer.parseInt(editNum.getText().toString().trim());
                    if (buy_num > 1) {
                        buy_num--;
                        editNum.setText(buy_num + "");
                    }
                }
                CalculationPrice();
                break;
            case R.id.btn_plus:

                if (editNum.getText().toString().trim().equals("")) {
                    editNum.setText("1");
                } else if (typeid == 5 || typeid == 6) {
                    editNum.setText("1");
                    ObjectUtils.toast(mcontext, "最多只能购买数量1");

                } else {
                    buy_num = Integer.parseInt(editNum.getText().toString().trim());
                    if (buy_num < buy_num_limit) {
                        buy_num++;
                        editNum.setText(buy_num + "");

                    } else {
                        ObjectUtils.toast(mcontext, "没有更多库存了");
                    }
                }
                CalculationPrice();
                break;
            case R.id.pay_address_add_ll:
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 0);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_NUMBER, 2);
                startActivity(intent);
                break;
            case R.id.pay_address_ll:
                Intent intent_address = new Intent(this, BaseObject.class);
                intent_address.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "收货地址");
                startActivityForResult(intent_address,0);
                break;
            case R.id.click_resetnetwork_refresh:
                break;
            case R.id.pay_post:
                buy_num = Integer.parseInt(editNum.getText().toString().trim());
                String msg = payMsgEdit.getText().toString().trim();
                if (addressid == null) {
                    ObjectUtils.toast(mcontext, "请选择收货地址");
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 0);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_NUMBER, 2);
                    startActivity(intent);
                    return;
                }

                GetToPay(token, buy_num, addressid, express_id, take_address_id,pay_id, coupon_id_use_general, msg, coupon_id_use_store);



                break;
            case R.id.pay_coupon_store_ll:
                final PopPaycoupn pop_store = new PopPaycoupn(mcontext, data, pos_use_store);
                pop_store.show(mcontext.getWindow().getDecorView(), 1);
                pop_store.setPopListDataClickListener(new PopPaycoupn.OnPopListDataClickListener() {
                    @Override
                    public void onData(String id, String discount, String need_amount, String title, int posUse, int type) {
                        if (type == 1) {
                            pos_use_store = posUse;
                            coupon_id_use_store = id;
                            coupon_discount_use_store = discount;
                            coupon_need_amount_use_store = need_amount;
                            coupon_title_use_store = title;
                            if (Double.parseDouble(coupon_need_amount_use_store) > (price_team * buy_num)) {
                                pos_use_store = 0;
                                coupon_id_use_store = "0";
                                coupon_discount_use_store = "0";
                                coupon_need_amount_use_store = "-1";
                                coupon_title_use_store = "不满足优惠";

                            }
                            payCouponStoreTv.setText(coupon_title_use_store);
                        }
                        pop_store.close();
                        CalculationPrice();
                    }
                });
                break;
            case R.id.pay_coupon_general_ll:
                //优惠券通用
                final PopPaycoupn pop_general = new PopPaycoupn(mcontext, data, pos_use_general);
                pop_general.show(mcontext.getWindow().getDecorView(), 0);
                pop_general.setPopListDataClickListener(new PopPaycoupn.OnPopListDataClickListener() {
                    @Override
                    public void onData(String id, String discount, String need_amount, String title, int posUse, int type) {
                        if (type == 0) {
                            pos_use_general = posUse;
                            coupon_id_use_general = id;
                            coupon_discount_use_general = discount;
                            coupon_need_amount_use_general = need_amount;
                            coupon_title_use_general = title;
                            if (Double.parseDouble(coupon_need_amount_use_general) > sub(price_team * buy_num, Double.parseDouble(coupon_discount_use_store))) {
                                pos_use_general = 0;
                                coupon_id_use_general = "0";
                                coupon_discount_use_general = "0";
                                coupon_need_amount_use_general = "-1";
                                coupon_title_use_general = "不满足优惠";

                            }
                            payCouponGeneralTv.setText(coupon_title_use_general);
                        }


                        pop_general.close();
                        CalculationPrice();
                    }
                });
                break;
        }

    }

    private Double price_pay;

    private void CalculationPrice() {

        double price_total = sub(price_team * buy_num, Double.parseDouble(coupon_discount_use_store));
        price_pay = sub(price_team * buy_num, (Double.parseDouble(coupon_discount_use_general)
                + Double.parseDouble(coupon_discount_use_store) + discount_teamer));

        payPriceTotal.setText("￥" + price_total);
        if (typeid == 10) {
            payPricePay.setText("￥" + (deposit * buy_num));
        } else {
            payPricePay.setText("￥" + price_pay);
        }

        if (price_total < 0) {
            payPriceTotal.setText("￥0");

        }

        if (price_pay < 0) {
            payPricePay.setText("￥0");
        }

        MyLog.e("返回通用", coupon_id_use_general + "优惠" + coupon_discount_use_general + "满" + coupon_need_amount_use_general + coupon_title_use_general);
        MyLog.e("返回店铺", coupon_id_use_store + "优惠" + coupon_discount_use_store + "满" + coupon_need_amount_use_store + coupon_title_use_store);
        MyLog.e("数量", buy_num + "支付" + price_pay);
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }


    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }


    @Override
    public void afterTextChanged(Editable s) {

        if (editNum.getText().toString().trim().equals("")) {
            payPriceTotal.setText("￥0");
            payPricePay.setText("￥0");
            return;
        }
        buy_num = Integer.parseInt(editNum.getText().toString().trim());
        if (buy_num <= 0) {
            editNum.setText("1");
            ObjectUtils.toast(mcontext, "数量必须大于0");
            return;

        }
        if (buy_num > buy_num_limit) {
            editNum.setText(buy_num_limit + "");
            ObjectUtils.toast(mcontext, "没有更多库存了");
            return;

        }
        CalculationPrice();

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        // 根据上面发送过去的请求吗来区别
        switch (requestCode) {
            case 0:
                buy_num = Integer.parseInt(editNum.getText().toString().trim());
                Getdata(detail_id, buy_num, typeid + "", spec, common_id, option);
                break;
            default:
                break;
        }
    }



    //获取订单数据
    private void Getdata(String id, int num, final String typeid, String spec, String common_id, String option) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERPAY;
        MyLog.e("地址", "" + address);
        if (networkConnected) {
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);

            HashMap<String, String> map = new HashMap<>();
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            map.put("id", id);
            map.put("num", num+ "");
            map.put("typeid", typeid);//商品类型
            map.put("spec", spec);//商品规格
            if(common_id==null)
            {
                common_id="";
            }
            map.put("common_id", common_id);//参团所需要的团ID
            map.put("option", option);//自选
            MyLog.e("chanpinid", id);
            MyLog.e("common_id", common_id);
            MyLog.e("option", option);
            MyLog.e("spec", spec);
            MyLog.e("typeid", typeid);
            HttpUtils.post(address, header, map, new paydetailCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                        }

                        @Override
                        public void onResponse(paydetail response, int id) {

                            if (response.getCode() == 0) {
                                data = response.getData();

                                if (data != null) {
                                    //是否添加地址
                                    if (data.getAddress() != null) {
                                        payAddressLl.setVisibility(View.VISIBLE);
                                        payAddressAddLl.setVisibility(View.GONE);
                                        payAddressNameaphone.setText(data.getAddress().getName() + "," + data.getAddress().getMobile());

                                        payAddressAddress.setText(data.getAddress().getArea() + data.getAddress().getAddress());
                                        addressid = data.getAddress().getId() + "";
                                        if(data.getTake_address()!=null&&data.getExpress()!=null) {
                                            express_id = data.getExpress().get(0).getId();
                                            take_address_id = data.getTake_address().get(0).getId();
                                        }
                                    } else {
                                        //手动创建地址
                                        payAddressAddLl.setVisibility(View.VISIBLE);
                                        payAddressLl.setVisibility(View.GONE);

                                    }
                                    //支付方式
                                    mSortListdata.clear();
                                    if(data.getPayment()!=null) {
                                        for (int i = 0; i < data.getPayment().size(); i++) {
                                            pay_ids[i] = data.getPayment().get(i).getPay_id() + "";
                                            if (data.getPayment().get(i).getPay_code().equals("wxpayapp")) {
                                                mSortListdata.add(new MainTabData("微信", pay_ids[i], R.mipmap.support_pay_wx));
                                            }
                                            if (data.getPayment().get(i).getPay_code().equals("alipayapp")) {
                                                mSortListdata.add(new MainTabData("支付宝", pay_ids[i], R.mipmap.support_pay_ali));
                                            }
                                        }
                                        pay_id = pay_ids[0];
                                        pay_style = mSortListdata.get(0).getName();
                                    }
                                    //        mSortListdata.add(new MainTabData("银联(未开通)", "", R.mipmap.support_pay_yl));
                                    payStyleList.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_pay, mSortListdata) {
                                        @Override
                                        public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                                            holder.setText(R.id.pay_name, testBean.getName());
                                            holder.setImageResource(R.id.pay_logo, testBean.getThumb());

                                            if (pospay == position) {//最后选择的位置
                                                holder.setChecked(R.id.item_list_mine_pay_check, true);
                                            } else {
                                                holder.setChecked(R.id.item_list_mine_pay_check, false);
                                            }

                                        }
                                    });

                                    payStyleList.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(NestFullListView nestFullListView, View view, int position) {
                                            pospay = position;
                                            nestFullListView.updateUI();
                                            pay_id=mSortListdata.get(position).getId();
                                            pay_style = mSortListdata.get(position).getName();
                                        }
                                    });

                                    payStyleList.updateUI();

                                    //商品标题头像等
                                    payGoodsPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                                    payGoodsTitle.setText(data.getGoods().getName());
                                    String store_name = data.getStore_name();
                                    if (store_name != null) {
                                        payGoodsStoreName.setText(store_name + "");
                                    } else {
                                        payGoodsStoreName.setText("轻松团商城自营");

                                    }
                                    ObjectUtils.photo(mcontext, data.getGoods().getImg_cover(), payGoodsThumb);
                                    payGoodsPrice.setText("￥" + data.getGoods().getMarket_price());
                                    Object goods_spec = data.getGoods().getGoods_spec();
                                    if (goods_spec != null) {
                                        payGoodsPriceSpec.setText((String) goods_spec);
                                    }
                                    //团购价
                                    price_team = Double.parseDouble(data.getGoods().getPrice());
                                    payGoodsPriceTeam.setText("￥" + price_team);
                                    buy_num_limit = data.getGoods().getBuy_num_limit();
                                    price_pay = Double.parseDouble(data.getGoods().getSubtotal());


                                    //团长优惠
                                    String discount_amount = data.getGoods().getDiscount_amount();
                                    if (discount_amount == null || discount_amount.equals("0.00") || discount_amount.equals("0")) {
                                        discount_teamer = 0.0;
                                        payCouponTeamerLl.setVisibility(View.GONE);


                                    } else {
                                        payCouponTeamerLl.setVisibility(View.VISIBLE);
                                        discount_teamer = Double.parseDouble(discount_amount);

                                    }
                                    payCouponTeamerTv.setText("-￥" + discount_teamer);
                                }

                                payPriceTotal.setText("￥" + price_pay);
                                if (typeid.equals("10")) {
                                    payPriceDepositLl.setVisibility(View.VISIBLE);
                                    deposit = Double.parseDouble(data.getGoods().getDeposit());
                                    payPriceDeposit.setText("￥" + deposit);
                                    payCouponGeneralLl.setVisibility(View.GONE);
                                    payCouponStoreLl.setVisibility(View.GONE);
                                    payCouponTeamerLl.setVisibility(View.GONE);
                                    payPricePay.setText("￥" + deposit);
                                    payTip.setText("支付定金后请在72小时内分享到微信朋友圈邀请好友一起拼团呦，阶梯团根据拼团人数价格会不断变动，"
                                            + "因此采取在预定款上加补差额的方式，如果有客户不补齐尾款的话，阶梯团也不会把定金退给客户。");
                                } else {
                                    payPricePay.setText("￥" + price_pay);
                                    payTip.setText("付款完成后请分享到微信朋友圈邀请好友一起拼团吧~，超过72小时后人数不足系统自动退款");
                                }
                                token = data.getToken();

                                List<paydetail.DataBean.TakeAddressBean> take_address = data.getTake_address();
                                if (take_address != null && take_address.size() > 0) {
                                    payAddressSelfLl.setVisibility(View.VISIBLE);
                                    pay_address_self_empty_tv.setVisibility(View.GONE);
                                    initExpressself(take_address);
                                } else {
                                    payAddressSelfLl.setVisibility(View.GONE);
                                    pay_address_self_empty_tv.setVisibility(View.VISIBLE);
                                }
                                MyLog.e("token",token);
                                MyLog.e(" num + \"\"", buy_num + "");
                                MyLog.e("address_id",addressid);
                                MyLog.e("express_id",express_id);
                                MyLog.e("take_address_id",take_address_id);
                                MyLog.e("pay_id",pay_id);
                                MyLog.e("coupon_id",coupon_id_use_general);
                                MyLog.e("coupon_id_sid",coupon_id_use_store);
                                MyLog.e("order_tip","hahaha");
                                ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                            } else {
                                noData.setVisibility(View.VISIBLE);
                                noDataTv.setText(response.getMsg());
                                noDataTv.setVisibility(View.VISIBLE);
                            }
                        }
                    }

            );


        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "网络未连接");

        }
    }

    private void initExpressself(final List<paydetail.DataBean.TakeAddressBean> take_address) {

        payAddressSelfLl.setAdapter(new NestFullListViewAdapter<paydetail.DataBean.TakeAddressBean>(R.layout.item_pay_address, take_address) {
            @Override
            public void onBind(int position, paydetail.DataBean.TakeAddressBean testBean, NestFullViewHolder holder) {
                holder.setText(R.id.item_pay_address_detail, testBean.getArea() + testBean.getAddress());
                holder.setText(R.id.item_pay_address_phone, "电话：" + testBean.getMobile());

                if (posexpress == position) {//最后选择的位置
                    holder.setChecked(R.id.item_pay_address_check, true);
                } else {
                    holder.setChecked(R.id.item_pay_address_check, false);
                }

            }
        });

        payAddressSelfLl.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int position) {
                posexpress = position;
                nestFullListView.updateUI();
                take_address_id = take_address.get(position).getId();
            }
        });

    }

    //生成订单以及付款

    private void GetToPay(String token, int num, String address_id, String express_id, String take_address_id, final String pay_id, String coupon_id, String order_tip, String coupon_id_store) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERPAYDONE;
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW",getpd);
            MyLog.e("UID",getid);
            MyLog.e("UPSW",getpd);
            HashMap<String, String> map = new HashMap<>();
            map.put("token", token);
            map.put("num", num + "");
            map.put("address_id", address_id);//地址id
            map.put("express_id", express_id);//地址id
            map.put("take_address_id", take_address_id);//地址id
            MyLog.e("shishizhelidepay_id",pay_id);
            map.put("pay_id", pay_id);//支付方式id
            map.put("coupon_id", coupon_id);//优惠券id
            map.put("coupon_id_sid", coupon_id_store);//店铺优惠券id
            map.put("order_tip", order_tip);//买家留言

            if (pay_style.equals("支付宝")) {
                HttpUtils.post(address, header,map, new paydoneCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressLoading.setVisibility(View.GONE);
                    }

                    @Override
                    public void onResponse(paydone response, int id) {
                        if (response.isFlag()) {
                            order_sn = response.getData().getOrder_sn();
                            sharedPreferences = getSharedPreferences("wechat_temporary", 0); //私有数据
                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                            editor.putString(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ORDER_SN, order_sn);
                            editor.commit();//
                            isReallyOrder_flag = response.isFlag();

                            if (isReallyOrder_flag) {
                               if(response.getData().getPayment()!=null) {
                                   orderInfo = response.getData().getPayment();
                                   //支付宝支付发起
                                   Runnable payRunnable = new Runnable() {
                                       @Override
                                       public void run() {
                                           PayTask alipay = new PayTask(mcontext);
                                           Map<String, String> result = alipay.payV2(orderInfo, true);
                                           Log.i("msp", result.toString());
                                           Message msg = new Message();
                                           msg.what = SDK_PAY_FLAG;
                                           msg.obj = result;
                                           mHandler.sendMessage(msg);
                                       }
                                   };
                                   Thread payThread = new Thread(payRunnable);
                                   payThread.start();
                               }
                                else
                               {
                                   Intent intent_tuan = new Intent(mcontext, BaseObject.class);
                                   intent_tuan.putExtra("title", "团详情");
                                   intent_tuan.putExtra("need_id",response.getData().getCommon_id());
                                   mcontext.startActivity(intent_tuan);
                               }
                                progressLoading.setVisibility(View.GONE);
                            }
                        } else {
                             ObjectUtils.toast(mcontext,response.getMsg());
                            progressLoading.setVisibility(View.GONE);
                            return;
                        }
                    }
                });
            }
            else
            {
                HttpUtils.post(address,header, map, new wchatpaydoneCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressLoading.setVisibility(View.GONE);
                        finish();
                    }
                    @Override
                    public void onResponse(wchatpaydone response, int id) {
                        if (response.isFlag()) {
                            order_sn = response.getData().getOrder_sn();
                            sharedPreferences = getSharedPreferences("wechat_temporary", 0); //私有数据
                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                            editor.putString(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ORDER_SN, order_sn);
                            editor.commit();//
                            isReallyOrder_flag = response.isFlag();
                            if (isReallyOrder_flag) {
                                if(response.getData().getPayment()!=null) {
                                //微信支付发起
                                iwxapi = WXAPIFactory.createWXAPI(mcontext, ConstantsUrl.WX_APPID, true);
                                iwxapi.registerApp(ConstantsUrl.WX_APPID);
                                PayReq req = new PayReq();
                                req.appId = ConstantsUrl.WX_APPID;
                                req.partnerId = response.getData().getPayment().getPartnerid();
                                req.prepayId = response.getData().getPayment().getPrepayid();
                                req.packageValue = response.getData().getPayment().getWxpackage();
                                req.nonceStr = response.getData().getPayment().getNoncestr();
                                req.timeStamp = response.getData().getPayment().getTimestamp();
                                req.sign = response.getData().getPayment().getSign();
                                iwxapi.sendReq(req);
                            }
                            }
                            else
                            {
                                Intent intent_tuan = new Intent(mcontext, BaseObject.class);
                                intent_tuan.putExtra("title", "团详情");
                                intent_tuan.putExtra("need_id",response.getData().getCommon_id());
                                mcontext.startActivity(intent_tuan);
                            }
                            Timer timer = new Timer();// 实例化Timer类
                            timer.schedule(new TimerTask() {
                                public void run() {
                                    finish();
                                }
                            }, 3000);// 这里百毫秒
                                progressLoading.setVisibility(View.GONE);
                        } else {
                            ObjectUtils.toast(mcontext, response.getMsg());
                            progressLoading.setVisibility(View.GONE);
                            return;
                        }
                    }
                });
                }
        } else {
            ObjectUtils.toast(mcontext, "网络未连接");
        }

    }

    //支付成功去分享页面
    private void GetToSharePage()
    {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERPAYDONETOShare;
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW",getpd);
            HashMap<String, String> map = new HashMap<>();
            map.put("order_sn", order_sn);
            MyLog.e("order_snzhifubao",order_sn.toString());
            HttpUtils.get(address, header,map, new paydonetoshareCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    MyLog.e("call",call.toString());
                    MyLog.e("error",e.getMessage());
                    MyLog.e("error1",e.toString());
                    progressLoading.setVisibility(View.GONE);
                    finish();
                }

                @Override
                public void onResponse(paydonetoshare response, int id) {
                    MyLog.e("common_idzhibubao",response.getData().getCommon_id());
                    common_id = response.getData().getCommon_id();
                    if(Integer.parseInt(common_id)>0) {
                        Intent intent_tuan = new Intent(mcontext, BaseObject.class);
                        intent_tuan.putExtra("title", "团详情");
                        intent_tuan.putExtra("need_id", common_id);
                        mcontext.startActivity(intent_tuan);
                    }
                    else
                    {

                    }
                    MyLog.e("common_id100","111111");
                    progressLoading.setVisibility(View.VISIBLE);
                    finish();
                }


            });

        } else {
            ObjectUtils.toast(mcontext, "网络未连接");

        }
    }

    public double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

}